from utils.consts import TASK_CONF_PATH, INI_SECTION, BASIC_CONF_DICT, OPT_TASKS, CONF_TYPE
import configparser

GLOBAL_CONF = {k: v for k, v in BASIC_CONF_DICT.items()}


def read_conf(conf_name: str):
    # read config ini file
    con = configparser.ConfigParser()
    con.read(f"{TASK_CONF_PATH}/{conf_name}.ini", encoding="utf-8")
    # read basic section
    if not con.has_section(INI_SECTION):
        return None
    # ini file is matched with defualt GLOBAL_CONF
    # if ini.get fail, then using default settings
    for key in GLOBAL_CONF.keys():
        try:
            GLOBAL_CONF[key] = con.get(INI_SECTION, key)
        except:
            if key == 'task':
                return False
    # different task's own settings
    # ini get fail, the using default settings
    task_sect = GLOBAL_CONF['task']
    if task_sect not in OPT_TASKS.keys():
        return False
    distr_flag = GLOBAL_CONF['distr']
    for k, v in OPT_TASKS[task_sect].items():
        try:
            GLOBAL_CONF[k] = con.get(task_sect, k)
        except:
            GLOBAL_CONF[k] = v

    # adjust type
    for k, v in GLOBAL_CONF.items():
        GLOBAL_CONF[k] = CONF_TYPE[k](v)
    GLOBAL_CONF['distr_flag'] = distr_flag
    return True


def update_conf(append_dict: dict):
    for k, v in append_dict.items():
        GLOBAL_CONF[k] = v


def get_gpu():
    return GLOBAL_CONF['gpu']
